package com.ley.springboot.commons.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;

/**
 * ApplicationContext holder
 *
 * @author 2036185346@qq.com
 * @see ApplicationContextAware
 **/
public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.applicationContext = applicationContext;
    }

    /**
     * Get bean from IOC container
     *
     * @see org.springframework.beans.factory.BeanFactory#getBean(String, Class)
     **/
    public static <T> T getBean(String beanName, Class<T> requireType) {
        return applicationContext.getBean(beanName, requireType);
    }


    /**
     * Get bean from IOC container
     *
     * @see org.springframework.beans.factory.BeanFactory#getBean(String)
     **/
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }


    /**
     * Get bean from IOC container
     *
     * @see org.springframework.beans.factory.BeanFactory#getBean(Class)
     **/
    public static <T> T getBean(Class<T> requireType) {
        return applicationContext.getBean(requireType);
    }


    /**
     * Get environment
     *
     * @see org.springframework.context.ConfigurableApplicationContext#getEnvironment()
     **/
    public static Environment getEnvironment() {
        return applicationContext.getEnvironment();
    }


    /**
     * IOC container whether contains bean name is beanName
     *
     * @see org.springframework.beans.factory.BeanFactory#containsBean(String)
     **/
    public static boolean containsBean(String beanName) {
        return applicationContext.containsBean(beanName);
    }


    /**
     * IOC container contains BeanDefinition names
     *
     * @see org.springframework.beans.factory.ListableBeanFactory#getBeanDefinitionNames()
     **/
    public static String[] getBeanDefinitionNames() {
        return applicationContext.getBeanDefinitionNames();
    }


    /**
     * get bean names for type
     *
     * @see org.springframework.beans.factory.ListableBeanFactory#getBeanNamesForType(Class)
     **/
    public static String[] getBeanNamesForType(Class<?> type) {
        return applicationContext.getBeanNamesForType(type);
    }
}
